package com.lebang.medicalInquiry.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lebang.medicalInquiry.constant.BusinessEnum;
import com.lebang.medicalInquiry.exception.BusinessException;
import com.lebang.medicalInquiry.mapper.*;
import com.lebang.medicalInquiry.model.po.*;
import com.lebang.medicalInquiry.model.vo.PageVo;
import com.lebang.medicalInquiry.model.vo.SubjectClassifyVo;
import com.lebang.medicalInquiry.model.vo.admin.PhysicianListVo;
import com.lebang.medicalInquiry.model.vo.admin.SubjectClassifyListVo;
import com.lebang.medicalInquiry.utils.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @author: zpc
 * @date:
 */
@Service
public class PhysicianService {
    @Resource
    private PhysicianMapper mapper;

    @Resource
    private PhysicianCaseMapper physicianCaseMapper;

    @Resource
    private PhysicianOrganizationRelevanceMapper physicianOrganizationRelevanceMapper;

    @Resource
    private SubjectClassifyMapper subjectClassifyMapper;

    @Resource
    private PhysicianVerbalTrickMapper physicianVerbalTrickMapper;

    @Resource
    private FigureVoiceMapper figureVoiceMapper;


    public PageVo<List<PhysicianListVo>> getList(String name, Integer classifyId, Integer organizationId, String organizationOperatorUuid, Integer state, Integer page, Integer limit) {
        List<PhysicianListVo> list = mapper.listByCondition(name, classifyId, state, organizationId, organizationOperatorUuid, (page - 1) * limit, limit);
        Integer count = mapper.countByCondition(name, classifyId, state, organizationId, organizationOperatorUuid);
        return new PageVo<>(list, count);
    }

    // 添加风格 需要把现有题材的都进行同步
    public void operator(Physician po) {
        if (po.getId() == null) {
            po.setCreateTime(LocalDateTime.now());
            po.setUpdateTime(LocalDateTime.now());
            po.setState(1);
            mapper.insertSelective(po);

        } else {
            po.setUpdateTime(LocalDateTime.now());
            mapper.updateByPrimaryKey(po);
        }


    }

    // 删除医师
    public void remove(Integer id, String merchantId) {
        Physician physician = mapper.selectByPrimaryKey(id);
        mapper.deleteByPrimaryKey(id);
        // 删除给运营人员分配的记录
        physicianOrganizationRelevanceMapper.removeByPhysicianId(id);

        DigitalMataHttpUtil.removeDigitalProject(physician.getProjectId(), merchantId, "");
    }

    /**
     * 查询医师列表
     *
     * @param physicianId
     * @param page
     * @param limit
     * @return
     */
    public PageVo<List<PhysicianCase>> listPhysicianCase(Integer physicianId, Integer type, Integer page, Integer limit) {
        List<PhysicianCase> list = physicianCaseMapper.listByCondition(physicianId, type, (page - 1) * limit, limit);
        Integer count = physicianCaseMapper.countByCondition(physicianId, type);
        return new PageVo<>(list, count);

    }

    public void operatorCase(PhysicianCase po) {
        if (po.getId() == null) {
            po.setCreateTime(LocalDateTime.now());
            po.setUpdateTime(LocalDateTime.now());
            po.setState(1);
            physicianCaseMapper.insertSelective(po);

        } else {
            po.setUpdateTime(LocalDateTime.now());
            physicianCaseMapper.updateByPrimaryKey(po);
        }
    }

    public void removePhysicianCase(Integer id) {
        physicianCaseMapper.deleteByPrimaryKey(id);
    }

    /**
     * 获取推流连接
     *
     * @param physicianId 医师id
     * @param type        直播操作类型
     * @return
     */
    public void liveStatus(Integer physicianId, String type, String merchantId) {
        Physician physician = mapper.selectByPrimaryKey(physicianId);
        String projectId = physician.getProjectId();
        String qaShape = physician.getQaShape();
        if ("start".equals(type)) {
            if ("text".equals(qaShape) && TextUtil.isEmpty(physician.getVoiceId())) {
                throw new BusinessException("需要设置音频id");
            }
            String liveConfigJson = physician.getLiveConfigJson();
            String bgmUrl = "";
            Integer bgmVolume = 80;
            if (!TextUtil.isEmpty(liveConfigJson)) {
                JSONObject jsonObject = JSONObject.parseObject(liveConfigJson);
                bgmUrl = jsonObject.getString("bgmUrl");
                bgmVolume = jsonObject.getInteger("bgmVolume");
            }
            if (TextUtil.isEmpty(projectId)) {
                projectId = DigitalMataHttpUtil.createDigitalProject("medicalInquiry:" + physician.getId(), physician.getDhModelId(),
                        physician.getVoiceId() + "", merchantId, "",physician.getLiveBackgroundImg(),bgmUrl,bgmVolume);
                if (TextUtil.isEmpty(projectId)) {
                    throw new BusinessException("创建项目失败");
                }
                physician.setProjectId(projectId);
                mapper.updateByPrimaryKeySelective(physician);
            }

            List<PhysicianVerbalTrick> verbalTrick = physicianVerbalTrickMapper.getVerbalTrick(physicianId, null, physician.getQaShape(), 0, 1000);
            if (verbalTrick.size() == 0) {
                throw new BusinessException("话术库不可以为空");
            }
            // 调用修改项目属性接口
            FigureVoice figureVoice = figureVoiceMapper.selectByPrimaryKey(physician.getVoiceId());
            final boolean b = DigitalMataHttpUtil.updateDigitalProject(physician.getProjectId(), merchantId, physician.getDhModelId(), figureVoice.getSpeed(), figureVoice.getVolume(), physician.getVoiceId(),physician.getLiveBackgroundImg(),bgmUrl,bgmVolume);
            if (!b) {
                throw new BusinessException("项目属性修改失败");
            }
            JSONArray jsonArray = new JSONArray();
            verbalTrick.forEach(s -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("qa_id", s.getId());
                JSONArray answerArray = new JSONArray();
                if (BusinessEnum.trick_qa.getName().equals(s.getType())) {
                    if (physician.getQaShape().equals(BusinessEnum.qa_shape_text.getName())) {
                        answerArray = JSONObject.parseArray(s.getAnswerList());
                        jsonObject.put("voice_type", BusinessEnum.qa_shape_text.getType());
                    } else {
                        answerArray = JSONObject.parseArray(s.getVoiceAnswerList());
                        jsonObject.put("voice_type", BusinessEnum.qa_shape_url.getType());
                    }
                    jsonObject.put("qa_type", BusinessEnum.trick_qa.getType());
                    jsonObject.put("answer", answerArray);
                } else {
                    List<String> array = new ArrayList<>();
                    if (physician.getQaShape().equals(BusinessEnum.qa_shape_text.getName())) {
                        array.add(s.getSingleAnswer());
                        jsonObject.put("answer", JSONObject.parseArray(JSONObject.toJSONString(array)));
                        jsonObject.put("voice_type", BusinessEnum.qa_shape_text.getType());

                    } else {
                        jsonObject.put("voice_type", BusinessEnum.qa_shape_url.getType());
                        array.add(s.getSingleUrlAnswer());
                        jsonObject.put("answer", JSONObject.parseArray(JSONObject.toJSONString(array)));
                    }
                    jsonObject.put("qa_type", BusinessEnum.trick_convention.getType());
                }
                jsonObject.put("question", s.getKeywords());
                jsonArray.add(jsonObject);
            });
            // 上传问答对
            final boolean qaResult = DigitalMataHttpUtil.batchUploadQaList(projectId, merchantId, "", jsonArray);
            if (!qaResult) {
                throw new BusinessException("批量上传问答对失败");
            }

            physician.setIsLive(BusinessEnum.live_status_resouce_ing.getType());
            mapper.updateByPrimaryKeySelective(physician);
        } else {
            DigitalMataHttpUtil.closeLive(projectId, merchantId, "", physician.getLiveRoomId());
            physician.setIsLive(BusinessEnum.NO.getType());
            physician.setLiveRoomId(null);
            physician.setPullStreamUrl(null);
            physician.setIsLive(BusinessEnum.live_status_no_start.getType());
            mapper.updateByPrimaryKey(physician);
        }


    }

    public PageVo<List<SubjectClassifyListVo>> listClassify(Integer parentId, Integer state, Integer page, Integer limit) {

        return new PageVo<>(subjectClassifyMapper.listClassify(parentId, state, (page - 1) * limit, limit), subjectClassifyMapper.countClassify(parentId, state));
    }

    public void operatorClassify(SubjectClassify subjectClassify) {
        if (subjectClassify.getId() == null) {
            subjectClassify.setCreateTime(LocalDateTime.now());
            subjectClassify.setUpdateTime(LocalDateTime.now());
            subjectClassify.setState(1);
            subjectClassifyMapper.insertSelective(subjectClassify);

        } else {
            subjectClassify.setUpdateTime(LocalDateTime.now());
            subjectClassifyMapper.updateByPrimaryKey(subjectClassify);
        }
    }

    public void removeClassify(Integer id) {
        subjectClassifyMapper.deleteByPrimaryKey(id);
        subjectClassifyMapper.deleteByParentId(id);
    }

    /**
     * 查询所有职位
     *
     * @return
     */
    public List<String> getAllPosition() {
        return mapper.getAllPosition();
    }

    public PageVo<List<PhysicianVerbalTrick>> getVerbalTrick(Integer physicianId, String type, Integer page, Integer limit) {
        final Physician physician = mapper.selectByPrimaryKey(physicianId);
        return new PageVo<List<PhysicianVerbalTrick>>(physicianVerbalTrickMapper.getVerbalTrick(physicianId, type, physician.getQaShape(), (page - 1) * limit, limit), physicianVerbalTrickMapper.count(physicianId, type, physician.getQaShape()));
    }

    public void modifyTrick(PhysicianVerbalTrick physicianVerbalTrick, String merchantId) {

        if (physicianVerbalTrick.getId() != null) {
            physicianVerbalTrickMapper.updateByPrimaryKeyWithBLOBs(physicianVerbalTrick);
        } else {
            physicianVerbalTrick.setCreateTime(LocalDateTime.now());
            physicianVerbalTrick.setUpdateTime(LocalDateTime.now());
            physicianVerbalTrick.setState(1);
            physicianVerbalTrickMapper.insertSelective(physicianVerbalTrick);
        }

    }

    public void removeTrick(Integer trickId, String merchantId) {
        String physicianId = physicianVerbalTrickMapper.selectByPrimaryKey(trickId).getPhysicianId();
        Physician physician = mapper.selectByPrimaryKey(Integer.parseInt(physicianId));
        DigitalMataHttpUtil.deleteQaList(physician.getProjectId(), merchantId, "", trickId);
        physicianVerbalTrickMapper.deleteByPrimaryKey(trickId);
    }


    public Integer schedule(Integer physicianId, String merchantId) {
        Physician physician = mapper.selectByPrimaryKey(physicianId);
        return DigitalMataHttpUtil.querySchedule(physician.getProjectId(), merchantId, "");
    }

    public void liveNotice(String projectId, String merchantId, String liveStatus) {
        Physician physician = mapper.getByProjectId(projectId);
        if ("start".equals(liveStatus)) {
            try {
                // 如果问答对不用修改会导致回调非常快, 导致在开播按钮操作的时候 IsLive被还原回-1  需要休眠下
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (physician != null) {
                JSONObject jsonObject = DigitalMataHttpUtil.startLive(projectId, merchantId, "", physician.getLiveBackgroundImg(), "text".equals(physician.getQaShape()) ? 1 : 2);
                if (jsonObject == null) {
                    System.out.println("开播失败");
                    physician.setIsLive(BusinessEnum.live_status_no_start.getType());
                    mapper.updateByPrimaryKeySelective(physician);
                } else {
                    String rtmpUrl = jsonObject.getString("rtmp_url");
                    String liveRoomId = jsonObject.getString("liveroom_id");
                    physician.setPullStreamUrl(rtmpUrl);
                    physician.setLiveRoomId(liveRoomId);
                    physician.setIsLive(BusinessEnum.live_status_start.getType());
                    mapper.updateByPrimaryKeySelective(physician);
                }

            }
        } else {
            physician.setIsLive(BusinessEnum.NO.getType());
            physician.setLiveRoomId(null);
            physician.setPullStreamUrl(null);
            physician.setIsLive(BusinessEnum.live_status_no_start.getType());
            mapper.updateByPrimaryKey(physician);
        }

    }
}
